<template>
  <div class="statistics-page">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button @click="$router.push('/')" type="primary" plain>
          <el-icon><ArrowLeft /></el-icon>
          返回任务管理
        </el-button>
        <h1>📊 统计数据</h1>
      </div>
      <div class="header-right">
        <span>{{ userInfo.username }}</span>
        <el-button @click="handleLogout" type="danger" plain>退出登录</el-button>
      </div>
    </div>

    <!-- 统计内容 -->
    <div class="statistics-content">
      <!-- 时间范围选择器 -->
      <div class="time-range-selector">
        <el-card>
          <template #header>
            <span>📅 时间范围</span>
          </template>
          <el-radio-group v-model="selectedPeriod" @change="loadStatistics">
            <el-radio-button label="today">今日</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
          
          <div v-if="selectedPeriod === 'custom'" class="custom-date-range">
            <el-date-picker
              v-model="customDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="loadStatistics"
              style="margin-top: 15px;"
            />
          </div>
        </el-card>
      </div>

      <!-- 汇总统计卡片 -->
      <div class="stats-cards">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: #e6f7ff;">⏱️</div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryData.totalSessions }}</div>
              <div class="stat-label">总专注次数</div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: #f0f9ff;">⏰</div>
            <div class="stat-content">
              <div class="stat-value">{{ formatDuration(summaryData.totalDuration) }}</div>
              <div class="stat-label">总专注时长</div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: #fff7e6;">📊</div>
            <div class="stat-content">
              <div class="stat-value">{{ formatDuration(summaryData.avgDailyDuration) }}</div>
              <div class="stat-label">日均专注时长</div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background: #f6ffed;">📅</div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryData.activeDays }}</div>
              <div class="stat-label">活跃天数</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 当日专注数据 -->
      <div class="today-section">
        <el-card>
          <template #header>
            <div class="today-header">
              <span>📆 当日专注 {{ todayData.date }}</span>
            </div>
          </template>
          <div class="today-stats">
            <div class="today-stat-item">
              <span class="today-label">次数</span>
              <span class="today-value">{{ todayData.sessions }}</span>
            </div>
            <div class="today-stat-item">
              <span class="today-label">时长</span>
              <span class="today-value">{{ formatDuration(todayData.duration) }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <!-- 分类时间分配饼图 -->
        <el-card class="chart-card">
          <template #header>
            <span>🥧 专注时长分布</span>
          </template>
          <div v-loading="loading" class="chart-container">
            <div v-if="categoryData.length === 0 && !loading" class="empty-chart">
              <el-empty description="暂无专注数据，点击待办上的开始按钮来专注时间吧" />
            </div>
            <div v-else ref="categoryPieChart" class="chart"></div>
          </div>
        </el-card>

        <!-- 每日时长趋势图 -->
        <el-card class="chart-card">
          <template #header>
            <span>📈 每日时长趋势</span>
          </template>
          <div v-loading="loading" class="chart-container">
            <div v-if="dailyTrendData.length === 0 && !loading" class="empty-chart">
              <el-empty description="暂无趋势数据" />
            </div>
            <div v-else ref="dailyTrendChart" class="chart"></div>
          </div>
        </el-card>
      </div>

      <!-- 导出按钮 -->
      <div class="export-section">
        <el-button type="success" @click="handleExport" :loading="exporting">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { logout } from '../api/user'
import { 
  getStatisticsSummary, 
  getCategoryStatistics, 
  getDailyTrendStatistics,
  exportStatistics 
} from '../api/timer'
import * as echarts from 'echarts'

const router = useRouter()
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

// 数据状态
const loading = ref(false)
const exporting = ref(false)
const selectedPeriod = ref('week')
const customDateRange = ref([])

const summaryData = ref({
  totalSessions: 0,
  totalDuration: 0,
  avgDailyDuration: 0,
  activeDays: 0
})

const todayData = ref({
  date: '',
  sessions: 0,
  duration: 0
})

const categoryData = ref([])
const dailyTrendData = ref([])

// 图表实例
const categoryPieChart = ref(null)
const dailyTrendChart = ref(null)
let categoryChart = null
let dailyChart = null

// 格式化持续时长
const formatDuration = (seconds) => {
  if (!seconds) return '0分钟'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟`
  } else {
    return `${seconds}秒`
  }
}

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    const params = { period: selectedPeriod.value }
    
    // 如果是自定义范围，添加日期参数
    if (selectedPeriod.value === 'custom' && customDateRange.value && customDateRange.value.length === 2) {
      params.startDate = customDateRange.value[0].toISOString().split('T')[0]
      params.endDate = customDateRange.value[1].toISOString().split('T')[0]
    }
    
    // 并行加载所有数据
    const [summaryRes, categoryRes, dailyRes] = await Promise.all([
      getStatisticsSummary(params),
      getCategoryStatistics(params),
      getDailyTrendStatistics(params)
    ])
    
    // 更新汇总数据
    summaryData.value = summaryRes.data
    todayData.value = summaryRes.data.todayData
    
    // 更新分类数据
    categoryData.value = categoryRes.data
    
    // 更新每日趋势数据
    dailyTrendData.value = dailyRes.data
    
    // 更新图表
    await nextTick()
    updateCharts()
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = () => {
  updateCategoryPieChart()
  updateDailyTrendChart()
}

// 更新分类饼图
const updateCategoryPieChart = () => {
  if (categoryData.value.length === 0) return
  
  if (!categoryChart && categoryPieChart.value) {
    categoryChart = echarts.init(categoryPieChart.value)
  }
  
  if (!categoryChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}秒 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center'
    },
    series: [
      {
        name: '专注时长',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: categoryData.value.map(item => ({
          name: item.categoryName,
          value: item.duration,
          itemStyle: {
            color: item.categoryColor
          }
        }))
      }
    ]
  }
  
  categoryChart.setOption(option)
}

// 更新每日趋势图
const updateDailyTrendChart = () => {
  if (dailyTrendData.value.length === 0) return
  
  if (!dailyChart && dailyTrendChart.value) {
    dailyChart = echarts.init(dailyTrendChart.value)
  }
  
  if (!dailyChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0]
        const minutes = Math.floor(data.value / 60)
        return `${data.name}<br/>时长: ${minutes}分钟`
      }
    },
    xAxis: {
      type: 'category',
      data: dailyTrendData.value.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '时长(分钟)',
      axisLabel: {
        formatter: value => Math.round(value / 60)
      }
    },
    series: [
      {
        data: dailyTrendData.value.map(item => item.duration),
        type: 'line',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.05)'
            }]
          }
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  dailyChart.setOption(option)
}

// 导出数据
const handleExport = () => {
  exporting.value = true
  try {
    const params = { period: selectedPeriod.value, format: 'csv' }
    
    if (selectedPeriod.value === 'custom' && customDateRange.value && customDateRange.value.length === 2) {
      params.startDate = customDateRange.value[0].toISOString().split('T')[0]
      params.endDate = customDateRange.value[1].toISOString().split('T')[0]
    }
    
    exportStatistics(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

// 登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await logout()
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('timerState')
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('登出失败:', error)
    }
  }
}

// 窗口大小改变时调整图表
const handleResize = () => {
  if (categoryChart) categoryChart.resize()
  if (dailyChart) dailyChart.resize()
}

onMounted(() => {
  loadStatistics()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (categoryChart) categoryChart.dispose()
  if (dailyChart) dailyChart.dispose()
})
</script>

<style scoped>
.statistics-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 0 20px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.statistics-content {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.time-range-selector {
  margin-bottom: 20px;
}

.custom-date-range {
  margin-top: 15px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.today-section {
  margin-bottom: 20px;
}

.today-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.today-stats {
  display: flex;
  gap: 40px;
  justify-content: center;
  padding: 20px 0;
}

.today-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.today-label {
  font-size: 14px;
  color: #909399;
}

.today-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 450px;
}

.chart-container {
  height: 380px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.empty-chart {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.export-section {
  text-align: center;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .today-stats {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
